package com.gcp.ai.service.impl;

import com.alibaba.cloud.ai.tongyi.audio.TongYiAudioSpeechClient;
import com.alibaba.cloud.ai.tongyi.audio.api.SpeechPrompt;
import com.alibaba.cloud.ai.tongyi.audio.api.SpeechResponse;
import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesClient;
import com.gcp.ai.service.AiService;
import com.gcp.ai.service.SseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;

@Service
@Slf4j
public class TongyiServiceImpl implements AiService {

    private final TongYiChatClient chatClient;

    private final TongYiImagesClient imageClient;

    private final TongYiAudioSpeechClient audioClient;

    private final SseService sseService;

    @Autowired
    public TongyiServiceImpl(TongYiChatClient chatClient, TongYiImagesClient imageClient, TongYiAudioSpeechClient audioClient, SseService sseService) {
        this.chatClient = chatClient;
        this.imageClient = imageClient;
        this.audioClient = audioClient;
        this.sseService = sseService;
    }

    /**
     * 问答
     * @param message
     * @return
     */
    @Override
    public String completion(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        ChatResponse chatResponse = chatClient.call(prompt);
        return chatResponse.getResult().getOutput().getContent();
    }

    /**
     * 文生图
     * @param imgPrompt
     * @return
     */
    @Override
    public String getImg(String imgPrompt){
        var prompt = new ImagePrompt(imgPrompt);
        return imageClient.call(prompt).getResult().getOutput().getUrl();
    }

    /**
     * 文字内容转化为音频
     * @param audioPrompt
     * @return
     */
    @Override
    public void getAudio(String audioPrompt){
        var prompt = new SpeechPrompt(audioPrompt);
        ByteBuffer audioData = audioClient.call(prompt).getResult().getOutput();
        try (FileOutputStream fos = new FileOutputStream("output.mp3")) {
            // 写入音频数据
            fos.write(audioData.array(), audioData.arrayOffset() + audioData.position(), audioData.remaining());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void chat(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        Flux<ChatResponse> flux = chatClient.stream(prompt);
        flux.subscribe(chatResponse -> {
            sseService.sendMessage("1",chatResponse.getResult().getOutput().getContent());
        });
    }

}
